import { defineStore } from "pinia";
import { ref } from "vue";
import { constantRoutes } from '@/router/_routes'
import router, {dynamicRoutes} from "@/router";
import {loginListMyMenu, listMenu} from "@/api/system/menu";
import { handleTree } from '@/utils/utro'
import Layout from '@/layout/index'
// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../../views/**/*.vue')

export const usePermissionStore = defineStore('permission', () => {
    const routes = ref([]);
    const hasinit = ref(false)
    const isCollapse = ref(false)

    function setRoutes(routeArr) {
        routes.value = routeArr
    }

    function setInit(flag){
        hasinit.value = flag
    }
    function treeRoutes(arr){
      if(arr && arr.length){
        arr.forEach(el=>{
          el.name = el.menuUrl;
          if(arr.children && arr.children.length){
            treeRoutes(arr.children)
          }
        })
      }
    }
    const generateRoutes = () => {
        // formatRoutes(constantRoutes)
        return new Promise(resolve => {
          // 向后端请求路由数据
          // loginListMyMenu({}).then(res => {
          listMenu({time: 2}).then(res => {
            let trData = handleTree(res.data, "menuId", 'menuUpId');
            console.log(2222)
            console.log(trData)
            console.log(constantRoutes)
            let asyncRoutes = filterAsyncRouter(trData)
            // let asyncRoutes = filterAsyncRouter(constantRoutes)
            asyncRoutes.forEach(routeRow => {
                  router.addRoute(routeRow)
            })
            // dynamicRoutes.forEach(routeRow => {
            //   router.addRoute(routeRow)
            // })
            // console.log(constantRoutes)
            console.log(asyncRoutes)
            console.log('asyncRoutes')
            setRoutes(asyncRoutes.concat(dynamicRoutes))
            setInit(true)
            resolve(asyncRoutes.concat(dynamicRoutes))
          })
        })
    }
    
    return { routes,hasinit,isCollapse, setRoutes,setInit ,generateRoutes}
})

function formatRoutes(routes){
    routes.forEach( obj => {
        let componentStr = `/src/${obj.component}.vue`
        obj.component = modules[componentStr]
        if(obj.children && obj.children.length > 0){
            formatRoutes(obj.children)
        }
    })
}
export const loadView = (view) => {
    let res;
    for (const path in modules) {
        const dir = path.split('views/')[1].split('.vue')[0];
        if (dir === view) {
        res = () => modules[path]();
        }
    }
    console.log(666)
    return res;
}
// 遍历路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false) {
    return asyncRouterMap.filter(route => {
      if (route.component) {
        // Layout 组件特殊处理
        if (route.component === 'Layout') {
          route.path = '/'+route.menuUrl;
          route.component = Layout
        } else {
          route.path = route.menuUrl;
          route.component = loadView(route.component)
        }
      }
      route.name = route.menuUrl;
      if (route.children != null && route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children)
      } else {
        delete route['children']
        delete route['redirect']
      }
      return true
    })
  }